package com.powernode.controller;


import com.powernode.common.Constants;
import com.powernode.common.Result;
import com.powernode.domain.User;
import com.powernode.service.UserService;
import com.powernode.utils.MD5Utils;
import com.powernode.utils.WebMvcUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
@RequestMapping("login")
public class LoginController {
    @Autowired
    private UserService userService;

    @PostMapping("doLogin.do")
    public Result doLogin(String username, String password, String captcha){
        System.out.println("1111");
        Object code = WebMvcUtils.getSession().getAttribute(Constants.CAPTCHA_CODE);
        if(code.equals(captcha)){
            User user=userService.login(username, MD5Utils.md5(password));
            if(null==user){
                return new Result(-1,"用户名或密码不正确");
            }
            WebMvcUtils.getSession().setAttribute(Constants.SESSION_USER_KEY,user);
            return new Result(200,"登陆成功");
        }else{
            return new Result(-1,"验证码不正确");
        }
    }

    @PostMapping("logout.do")
    public Result logout(){
        try {
            WebMvcUtils.getSession().invalidate();
            return Result.OPT_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return Result.OPT_ERROR;
        }
    }
}
